package com.zzh.lib.views.transform;


import android.view.View;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

/**
 * Created by ZZH on 2023/2/16.
 *
 * @date: 2023/2/16 14:46
 * @email: zzh_hz@126.com
 * @author: zzh
 * @description: com.zzh.lib.views.transform
 */
public class OverlayTransformer implements ViewPager.PageTransformer {

    private int overlayCount;
    private float scaleOffset = 40f, transOffset = 40f;

    public OverlayTransformer(int overlayCount, float scaleOffset, float transOffset) {
        this.overlayCount = overlayCount;
        this.scaleOffset = scaleOffset;
        this.transOffset = transOffset;
    }

    @Override
    public void transformPage(@NonNull View page, float position) {
        if (position <= 0.0f) { //当前页
            page.setTranslationX(0);
            page.setAlpha(1 - 0.5f * Math.abs(position));
            page.setClickable(true);
        } else {
            otherTrans(page, position);
            page.setClickable(false);
        }
    }

    private void otherTrans(View page, Float position) {
        //设置缩放比例
        float scale = (page.getWidth() - scaleOffset * position) / page.getWidth();
        page.setScaleX(scale);
        page.setScaleY(scale);
        page.setAlpha(1f);
        if (position > overlayCount - 1 && position < overlayCount) { //当前页向右滑动时,最右面第四个及以后页面应消失
            double curPositionOffset = transOffset * Math.floor(position); //向下取整
            double lastPositionOffset = transOffset * Math.floor((position - 1));//上一个卡片的偏移量
            float singleOffset = 1 - Math.abs(position % position);
            double transX = -page.getWidth() * position + (lastPositionOffset + singleOffset * (curPositionOffset - lastPositionOffset));
            page.setTranslationX((float) transX);
        } else if (position <= overlayCount - 1) {
            float transX = -page.getWidth() * position + transOffset * position;
            page.setTranslationX(transX);
        } else {
            page.setAlpha(0f);
        }
    }

    public int getOverlayCount() {
        return overlayCount;
    }
}
